package com.helloandroid.activitys

import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.AwardDialog
import com.helloandroid.dialogs.ZaoCanDialog
import com.helloandroid.models.butie.ChiFanViewModel
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.tools.MyTimeUtils.getOffsetTimeMs
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.ChiFanInfo

data class CFItem(var id: Int,
                  var startOffset: Long,
                  var endOffset: Long,
                  var desc: String,
                  var bitmapRes: Int,
                  val title: String,
                  val coin: Int) {
    val timeSegStr: String
        get() {
            val sb = StringBuilder()
            sb.append(MyTimeUtils.format_hhmm(startOffset))
            sb.append("-")
            sb.append(MyTimeUtils.format_hhmm(endOffset))
            return sb.toString()
        }
}


//// 这就是广为人知、为人诟病的垃圾 Kotlin 不支持 SAM 转换的情况。
//// 在 Kotlin 1.4 版本，你需要在接口前加上关键字 fun，让它成为一个 fun interface 才能享受到 SAM 转换。
//fun interface IItemUpdate {
//    // idx 从0 开始
//    fun changed()
//}

class ChiFanActivity : BaseActivity() {

    companion object {
        val dataLst: ArrayList<CFItem> = arrayListOf<CFItem>()

        init {
            // 早餐
            dataLst.add(CFItem(1,
                    getOffsetTimeMs(6, 0),
                    getOffsetTimeMs(10, 0),
                    "美好的一天从早餐开始~",
                    R.drawable.dd_canbu_zao,
                    "早餐补贴",
                    128
            ))

            // 午餐
            dataLst.add(CFItem(2,
                    getOffsetTimeMs(11, 0),
                    getOffsetTimeMs(13, 59),
                    "人是铁,饭是钢，午餐不吃饿得慌~",
                    R.drawable.dd_canbu_zhong,
                    "午餐补贴",
                    188
            ))

            // 下午茶
            dataLst.add(CFItem(3,
                    getOffsetTimeMs(14, 0),
                    getOffsetTimeMs(16, 29),
                    "放慢脚步, 给自己一杯下午茶，美好往往都在我们的热爱里~",
                    R.drawable.dd_canbu_xiawucha,
                    "下午茶补贴",
                    88
            ))

            // 晚餐补贴
            dataLst.add(CFItem(4,
                    getOffsetTimeMs(17, 30),
                    getOffsetTimeMs(19, 59),
                    "每一次晚餐都是对生活最深情的告白~",
                    R.drawable.dd_canbu_wan,
                    "晚餐补贴",
                    188
            ))

            // 宵夜补贴
            dataLst.add(CFItem(5,
                    getOffsetTimeMs(20, 0),
                    getOffsetTimeMs(23, 59),
                    "别让生活耗尽了你的耐心和向往，你还有诗和远方和夜宵~",
                    R.drawable.dd_canbu_xiaoye,
                    "宵夜补贴",
                    128
            ))
        }
    }

    var isReady = false
    var dstItem: CFItem? = null
    var mInfo: ChiFanInfo? = null

    val model: ChiFanViewModel by viewModels()

    // views
    private lateinit var tvWelcome: TextView
    private lateinit var tvTimeDesc: TextView
    private lateinit var tvDesc: TextView
    private lateinit var ivImg: ImageView
    private lateinit var tvItemDesc: TextView
    private lateinit var btnDaka: Button

    override fun getContentViewResId() = R.layout.activity_chifanbutie

    override fun initView() {

        tvWelcome = findViewById(R.id.tvWelcome)
        tvTimeDesc = findViewById(R.id.tvTimeDesc)
        tvDesc = findViewById(R.id.tvDesc)
        ivImg = findViewById(R.id.ivImg)
        tvItemDesc = findViewById(R.id.tvItemDesc)
        btnDaka = findViewById(R.id.btnDaka)

        // 返回
        findBtn(R.id.ibBack).setOnClickListener { finish() }

        // 打卡
        btnDaka.setOnClickListener {
            daka(dstItem) {

            }
        }

        // dialog
        findBtn(R.id.btnDialog).setOnClickListener {
            if (isReady) {
                ZaoCanDialog(this).show()
            }
        }

        SmallNativeAdUtil.showNativeAd(this,findViewById(R.id.nativeView))
    }

    override fun initData() {
        model.getInfo { success, info ->
            isReady = success
            if (isReady) {
                mInfo = info
                dstItem = null
                initUI()
            }
        }
    }

    fun daka(item: CFItem?, callback: (Boolean) -> Unit) {
        if (!isReady || item == null) {
            callback(false)
            return
        }

        if (!NetWorkUtil.networkConnected()) {
            callback(false)
            AppUtil.toast("请打开网络!")
            return
        }

        // 1.判断是否是补卡
        // 2.是哪一个打卡? 早 中 晚 ..
        val todayOffsetTime = MyTimeUtils.getTodayOffsetMs(AppUtil.sysTime)
        val video = todayOffsetTime !in item.startOffset..item.endOffset

        val reasonKey: String = when (item.id) {
            1 -> {
                if (video) Analyse.report(AnalyseKey.ChiFan_Zao_Video) else Analyse.report(AnalyseKey.ChiFan_Zao)
                AnalyseKey.ChiFan_Zao_Double
            }
            2 -> {
                if (video) Analyse.report(AnalyseKey.ChiFan_Zhong_Video) else Analyse.report(AnalyseKey.ChiFan_Zhong)
                AnalyseKey.ChiFan_Zhong_Double
            }
            3 -> {
                if (video) Analyse.report(AnalyseKey.ChiFan_XiaWu_Video) else Analyse.report(AnalyseKey.ChiFan_XiaWu)
                AnalyseKey.ChiFan_XiaWu_Double
            }
            4 -> {
                if (video) Analyse.report(AnalyseKey.ChiFan_Wan_Video) else Analyse.report(AnalyseKey.ChiFan_Wan)
                AnalyseKey.ChiFan_Wan_Double
            }
            else -> {
                if (video) Analyse.report(AnalyseKey.ChiFan_Xiaoye_Video) else Analyse.report(AnalyseKey.ChiFan_Xiaoye)
                AnalyseKey.ChiFan_Xiaoye_Double
            }
        }

        // 领取也需要看广告
        VideoAdUtil.playVideoAd(this) { success ->
            if (success) {
                realDaka(item, reasonKey)
                callback(true)
            } else {
                AppUtil.toast("视频还没准备好!")
                callback(false)
            }
        }
    }

    private fun realDaka(item: CFItem, reasonKey: String) {
        var awardCoin = item.coin
        AppUtil.appViewModel().chifanDaKa(item.id, awardCoin)
        mInfo?.setValueByChiFanId(item.id, 1)

        val dialog = AwardDialog(this, awardCoin)
        dialog.reasonKey = reasonKey
        dialog.show()

        // 更新UI. 如果是dialog里面领取的,可能不需要刷新下面的
        val selectedIdx = item.id - 1
        if (dstItem != null && selectedIdx == dstItem!!.id - 1) {
            updateUIByIdx(selectedIdx)
        }
    }

    private fun initUI() {
        val sysTime = AppUtil.sysTime
        var cfItem = getCfItem(sysTime)
        var selectedIdx: Int
        if (cfItem != null) {
            selectedIdx = cfItem.id - 1
        } else {
            cfItem = getNestestCfItem(sysTime)
            selectedIdx = if (cfItem != null) {
                cfItem.id - 1
            } else {
                // 直接显示最后一个
                dataLst.size - 1
            }
        }
        updateUIByIdx(selectedIdx)
    }

    private fun updateUIByIdx(idx: Int) {
        if (idx < 0) {
            return
        }
        val sysTime = AppUtil.sysTime
        tvWelcome.text = AppUtil.getWelComeName()
        var cfItem = dataLst[idx]
        val chifanInfo = mInfo!!
        val stateArr = chifanInfo.stateArr
        tvTimeDesc.text = MyTimeUtils.dayTimeString(sysTime)
        tvDesc.text = cfItem.desc
        ivImg.setImageResource(cfItem.bitmapRes)
        tvItemDesc.text = "${cfItem.title} ${cfItem.timeSegStr}"
        MyLog.elog("=======stateArr:$stateArr")
        MyLog.elog("=======cfItem:${cfItem.toString()}")
        if (stateArr[cfItem.id - 1] > 0) {
            btnDaka.setBackgroundResource(R.drawable.dd_btn_gray)
            btnDaka.text = "已经领取"
            dstItem = null
        } else {
            // 还未领取.
            // case1 时间到了 还没领取
            // case2 时间还没到
            val todayOffsetMs = MyTimeUtils.getTodayOffsetMs(sysTime)
            if (cfItem.startOffset <= todayOffsetMs &&
                    cfItem.endOffset >= todayOffsetMs) {
                // 可以领取
                btnDaka.setBackgroundResource(R.drawable.dd_btn_blue)
                btnDaka.text = "领取${cfItem.title}"
                dstItem = cfItem
            } else {
                // 时间未到
                dstItem = null
                btnDaka.text = "时间未到"
                btnDaka.setBackgroundResource(R.drawable.dd_btn_gray)
            }
        }
    }

    private fun getCfItem(time: Long): CFItem? {
        val dayStartMs = MyTimeUtils.getStartDayMs(time)
        for (hsItem in dataLst) {
            if (time >= dayStartMs + hsItem.startOffset &&
                    time <= dayStartMs + hsItem.endOffset) {
                return hsItem
            }
        }
        return null
    }

    private fun getNestestCfItem(time: Long): CFItem? {
        val dayStartMs = MyTimeUtils.getStartDayMs(time)
        for (cfItem in dataLst) {
            if (time < cfItem.startOffset + dayStartMs) {
                return cfItem
            }
        }
        return null
    }

    override fun isDarkMode() = false
}